<?php

namespace App\Http\Controllers\User;

use App\Models\Transaction;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TransactionController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['menu' => 'transaction']);
    }

    public function index(Request $request)
    {
        $queryParams = [
            'q' => '',
            'date_range' => 'all',
            'transaction_type' => 'all',
            'pay_type' => 'all',
        ];
        $query = Transaction::where(function (Builder $builder) {
            return $builder->where('payer_uid', $this->uid)->orWhere('payee_uid', $this->uid);
        });
        $date_range = $request->get('date_range', 'all');
        $queryParams['date_range'] = $date_range;
        $time = 0;
        $seconds = 86400;
        if ($date_range == '3days') {
            $time = time() - $seconds * 3;
        } elseif ($date_range == '7days') {
            $time = time() - $seconds * 7;
        } elseif ($date_range == 'oneMonth') {
            $time = time() - $seconds * 30;
        } elseif ($date_range == 'threeMonth') {
            $time = time() - $seconds * 90;
        } elseif ($date_range == 'oneYear') {
            $time = time() - $seconds * 365;
        }
        if ($time) {
            $query = $query->where('created_at', '>', $time);
        }

        $transaction_type = $request->get('transaction_type', 'all');
        if ($transaction_type != 'all') {
            $queryParams['transaction_type'] = $transaction_type;
            $query = $query->where('transaction_type', strtolower($transaction_type));
        }

        $pay_type = $request->get('pay_type', 'all');
        if ($pay_type != 'all') {
            $queryParams['pay_type'] = $pay_type;
            $query = $query->where('pay_type', $pay_type);
        }

        $q = $request->get('q');
        if ($q) {
            $queryParams['q'] = $q;
            $query = $query->where(function (Builder $builder) use ($q) {
                return $builder->where('subject', 'LIKE', "%$q%")->orWhere('detail', 'LIKE', "%$q%");
            });
        }

        $this->assign($queryParams);
        $items = $query->orderByDesc('transaction_id')->paginate(20);
        $wallet = $this->user()->wallet()->firstOrCreate([]);

        return $this->view('user.transaction.transactions', [
            'items' => $items,
            'pagination' => $items->appends($queryParams)->render(),
            'totalCount' => $items->total(),
            'wallet' => $wallet
        ]);
    }
}
